package edu.cs.usask.ca.silver.plugin.rcp.editors;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Table;

import edu.cs.usask.ca.silver.api.persistence.StorageI;
import edu.cs.usask.ca.silver.businesslogic.ids.BaseId;
import edu.cs.usask.ca.silver.businesslogic.ids.FileID;
import edu.cs.usask.ca.silver.businesslogic.ids.GroupID;
import edu.cs.usask.ca.silver.businesslogic.ids.ModelProjectID;
import edu.cs.usask.ca.silver.businesslogic.ids.ModelVersionID;
import edu.cs.usask.ca.silver.businesslogic.ids.ParameterID;
import edu.cs.usask.ca.silver.businesslogic.ids.ScenarioCollectionID;
import edu.cs.usask.ca.silver.businesslogic.ids.ScenarioID;
import edu.cs.usask.ca.silver.businesslogic.ids.SilverIDVisitor;
import edu.cs.usask.ca.silver.businesslogic.ids.UserID;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverNameEnums;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverPreferenceEntries;
import edu.cs.usask.ca.silver.plugin.rcp.dao.SilverBusinessLogicController;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.create.CreateScenarioDialog;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.create.CreateScenarioTableContentProvider;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.edit.SetInputFileToModelVersionDialog;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.simulations.RunAnylogicSimulationDialog;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.simulations.RunVensimSimulationDialog;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectView;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

public class InfoEditorCreatePanelSilverIDVisitorImpl implements
		SilverIDVisitor {

	private static Logger log = Logger
			.getLogger(InfoEditorCreatePanelSilverIDVisitorImpl.class);
	private InfoEditor infoEditor;
	private Composite top;
	private CreateScenarioTableContentProvider contentProvider;
	private ProjectViewI projectview;

	public InfoEditorCreatePanelSilverIDVisitorImpl(final Composite comp,
			final InfoEditor infoEditor) {
		this.top = comp;
		this.infoEditor = infoEditor;
	}

	protected BaseId getObjectId() {
		return ((InfoEditorInput) infoEditor.getEditorInput())
				.getModelObjectID();
	}

	@Override
	public void visit(UserID uId) throws Exception {
		// TODO Editorpane for User
	}

	@Override
	public void visit(GroupID gId) throws Exception {
		// TODO Editor pane for Group
		log.info("visit group");
	}

	/**
	 * A visitor method that generates the bottom part of a model project pane.
	 * 
	 * 
	 * @author Yudi Xue
	 * @param mprojectId
	 * @param composite
	 *            pane for elements to be added to, Array of baseID for the
	 *            selected model project
	 */
	@Override
	public void visit(final ModelProjectID mpId) throws Exception {
		Group mpAssociateFileGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		GridLayout layout = new GridLayout(2, false);
		mpAssociateFileGroup.setLayoutData(gridData);
		mpAssociateFileGroup.setLayout(layout);
		mpAssociateFileGroup.setText("Associate Files");

		final List associateFileList = new List(mpAssociateFileGroup, SWT.MULTI
				| SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.verticalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		associateFileList.setLayoutData(gridData);

		// ModelProjectLocalClient.getService().getAssociatedFileIds(mprojectId)
		// returns a FileID[]

		if (SilverBusinessLogicController.borrowMpObject()
				.getAssociatedFileIds(mpId, infoEditor.getAssociatedStorage()).length > 0) {
			// Get File Names and display in the List
			for (int j = 0; j < SilverBusinessLogicController.borrowMpObject()
					.getAssociatedFileIds(mpId,
							infoEditor.getAssociatedStorage()).length; j++) {
				try {
					// TODO simpler method?
					associateFileList
							.add(SilverBusinessLogicController
									.borrowFileObject()
									.getName(
											SilverBusinessLogicController
													.borrowMpObject()
													.getAssociatedFileIds(
															mpId,
															infoEditor
																	.getAssociatedStorage())[j],
											infoEditor.getAssociatedStorage()));
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}
		}

		Button addAssociateFile = new Button(mpAssociateFileGroup, SWT.PUSH
				| SWT.END);
		addAssociateFile.setText("Add..");

		addAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog file = new FileDialog(top.getShell(), SWT.OPEN);
				file.setFilterExtensions(new String[] { "*.*" });
				file.setFilterNames(new String[] { "Associate files (*.*)" });
				file.setText("Load Associate File:");

				File addFile = new File(file.open());
				try {
					FileID tempId = SilverBusinessLogicController
							.borrowFileObject().createFile(addFile.getName(),
									"Associate File for" + mpId.toString(),
									addFile.getAbsolutePath(),
									infoEditor.getAssociatedStorage());
					if (tempId == null) {
						MessageDialog.openError(
								top.getShell(),
								"Error adding associate files",
								"The associate file at "
										+ addFile.getAbsolutePath()
										+ " is not properly added.");
					}
					SilverBusinessLogicController.borrowFileObject()
							.addFileToModelProject(tempId, mpId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

				/*
				 * Refresh by removing all elements in List and add all files
				 * belong to this project again.
				 */
				associateFileList.removeAll();

				try {
					for (int j = 0; j < SilverBusinessLogicController
							.borrowMpObject().getAssociatedFileIds(mpId,
									infoEditor.getAssociatedStorage()).length; j++) {
						try {
							log.info("reloading file");
							associateFileList
									.add(SilverBusinessLogicController
											.borrowFileObject()
											.getName(
													SilverBusinessLogicController
															.borrowMpObject()
															.getAssociatedFileIds(
																	mpId,
																	infoEditor
																			.getAssociatedStorage())[j],
													infoEditor
															.getAssociatedStorage()));
						} catch (FileNotFoundException notFound) {
							MessageDialog.openError(top.getShell(),
									"File Open Error",
									"Please select an existing arbitrary file than a folder.");
						} catch (Exception e2) {
							log.error(e2.getMessage(), e2);
						}
					}
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

			}

		});

		Button removeAssociateFile = new Button(mpAssociateFileGroup, SWT.PUSH
				| SWT.END);
		removeAssociateFile.setText("Remove");
		removeAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to remove.");
					return;
				}

				int index;
				FileID[] temp = null;
				try {
					temp = SilverBusinessLogicController.borrowMpObject()
							.getAssociatedFileIds(mpId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e3) {
					log.error(e3.getMessage(), e3);
				}
				for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
					index = associateFileList.getSelectionIndices()[j];
					// Remove selected indexes
					try {
						SilverBusinessLogicController.borrowFileObject()
								.deleteFile(temp[index],
										infoEditor.getAssociatedStorage());
					} catch (Exception e1) {
						log.error(e1.getMessage(), e1);
					}
				}

				/*
				 * Refresh by removing all elements in List and add all files
				 * belong to this project again.
				 */
				associateFileList.removeAll();

				try {
					for (int k = 0; k < SilverBusinessLogicController
							.borrowMpObject().getAssociatedFileIds(mpId,
									infoEditor.getAssociatedStorage()).length; k++) {
						try {
							log.info("reloading file");
							associateFileList
									.add(SilverBusinessLogicController
											.borrowFileObject()
											.getName(
													SilverBusinessLogicController
															.borrowMpObject()
															.getAssociatedFileIds(
																	mpId,
																	infoEditor
																			.getAssociatedStorage())[k],
													infoEditor
															.getAssociatedStorage()));
						} catch (Exception e2) {
							log.error(e2.getMessage(), e2);
						}
					}
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

			}
		});

		Button createAssociateFile = new Button(mpAssociateFileGroup, SWT.PUSH
				| SWT.END);
		createAssociateFile.setText("Recreate");
		createAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to recreate.");
					return;
				}

				DirectoryDialog file = new DirectoryDialog(top.getShell(),
						SWT.SAVE);
				file.setText("Choose Directory :");
				file.setMessage("Select the Directory to save the Associate File:");
				final String directoryPath = file.open();
				if (directoryPath == null)
					return;

				int index;
				FileID[] temp = null;
				try {
					temp = SilverBusinessLogicController.borrowMpObject()
							.getAssociatedFileIds(mpId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e2) {
					log.error(e2.getMessage(), e2);
				}
				String fileName = null;
				String path = null;
				for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
					index = associateFileList.getSelectionIndices()[j];
					// Remove selected indexes
					try {
						path = directoryPath
								+ System.getProperty("file.separator")
								+ fileName;

						// get file name
						fileName = SilverBusinessLogicController
								.borrowFileObject().getName(temp[index],
										infoEditor.getAssociatedStorage());
						// combine recreate path
						SilverBusinessLogicController.borrowFileObject()
								.getFileToLocalStorage(temp[index], path,
										infoEditor.getAssociatedStorage());
					} catch (Exception e1) {
						log.error(e1.getMessage(), e1);
						MessageDialog.openError(top.getShell(),
								"Error during recreate",
								"Unable to recreate file, file of the same name exists");
					}
				}

				/*
				 * Refresh by removing all elements in List and add all files
				 * belong to this project again.
				 */
				associateFileList.removeAll();

				try {
					for (int k = 0; k < SilverBusinessLogicController
							.borrowMpObject().getAssociatedFileIds(mpId,
									infoEditor.getAssociatedStorage()).length; k++) {

						log.info("reloading file");
						associateFileList
								.add(SilverBusinessLogicController
										.borrowFileObject()
										.getName(
												SilverBusinessLogicController
														.borrowMpObject()
														.getAssociatedFileIds(
																mpId,
																infoEditor
																		.getAssociatedStorage())[k],
												infoEditor
														.getAssociatedStorage()));

					}
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

			}
		});

		SilverBusinessLogicController.returnAllFileObject();
		SilverBusinessLogicController.returnAllMpObject();
	}

	/**
	 * A method that display to needed data associated with the selected model
	 * version. The editor pane displays the parameter data information for all
	 * the parameters that make up the baseline scenario.
	 * 
	 * @param top
	 *            composite pane for this editor
	 * @param scenarioId
	 *            the baseline scenario for this model version
	 * @param parameterIds
	 *            array of parameter ids to populate table viewer from database
	 * @param mvId
	 *            unique id for identified ModelVersion
	 * @author Yudi Xue
	 */
	@Override
	public void visit(final ModelVersionID mvId) throws Exception {
		/*
		 * creating separate composite so it can span the original for alignment
		 * purposes my want to play with the number of columns
		 */

		Group mvAssociateFileGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		GridLayout layout = new GridLayout(2, false);
		mvAssociateFileGroup.setLayoutData(gridData);
		mvAssociateFileGroup.setLayout(layout);
		mvAssociateFileGroup.setText("Associate Files");

		final List associateFileList = new List(mvAssociateFileGroup, SWT.MULTI
				| SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.verticalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		associateFileList.setLayoutData(gridData);

		// ModelProjectLocalClient.getService().getAssociatedFileIds(mprojectId)
		// returns a FileID[]

		if (SilverBusinessLogicController.borrowMvObject()
				.getAssociatedFileIds(mvId, infoEditor.getAssociatedStorage()).length > 0) {
			// Get File Names and display in the List
			for (int j = 0; j < SilverBusinessLogicController.borrowMvObject()
					.getAssociatedFileIds(mvId,
							infoEditor.getAssociatedStorage()).length; j++) {
				associateFileList
						.add(SilverBusinessLogicController
								.borrowFileObject()
								.getName(
										SilverBusinessLogicController
												.borrowMvObject()
												.getAssociatedFileIds(
														mvId,
														infoEditor
																.getAssociatedStorage())[j],
										infoEditor.getAssociatedStorage()));
			}
		}

		Button addAssociateFile = new Button(mvAssociateFileGroup, SWT.PUSH
				| SWT.END);
		addAssociateFile.setText("Add..");

		addAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog file = new FileDialog(top.getShell(), SWT.OPEN);
				file.setFilterExtensions(new String[] { "*.*" });
				file.setFilterNames(new String[] { "Associate files (*.*)" });
				file.setText("Add Associate File:");

				File addFile = new File(file.open());
				FileID tempId;
				try {
					tempId = SilverBusinessLogicController.borrowFileObject()
							.createFile(addFile.getName(),
									"Associate File for" + mvId.toString(),
									addFile.getAbsolutePath(),
									infoEditor.getAssociatedStorage());
					if (tempId == null) {
						MessageDialog.openError(
								top.getShell(),
								"Error adding associate files",
								"The associate file at "
										+ addFile.getAbsolutePath()
										+ " is not properly added.");
					}
					SilverBusinessLogicController.borrowFileObject()
							.addFileToModelVersion(tempId, mvId,
									infoEditor.getAssociatedStorage());

					/*
					 * Refresh by removing all elements in List and add all
					 * files belong to this project again.
					 */
					associateFileList.removeAll();

					for (int j = 0; j < SilverBusinessLogicController
							.borrowMvObject().getAssociatedFileIds(mvId,
									infoEditor.getAssociatedStorage()).length; j++) {
						try {
							log.info("reloading file");
							associateFileList
									.add(SilverBusinessLogicController
											.borrowFileObject()
											.getName(
													SilverBusinessLogicController
															.borrowMvObject()
															.getAssociatedFileIds(
																	mvId,
																	infoEditor
																			.getAssociatedStorage())[j],
													infoEditor
															.getAssociatedStorage()));
						} catch (FileNotFoundException notFound) {
							MessageDialog.openError(top.getShell(),
									"File Open Error",
									"Please select an existing arbitrary file than a folder.");
						}
					}

				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
			}

		});

		Button removeAssociateFile = new Button(mvAssociateFileGroup, SWT.PUSH
				| SWT.END);
		removeAssociateFile.setText("Remove");
		removeAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to remove.");
					return;
				}

				int index;
				FileID[] temp;
				try {
					temp = SilverBusinessLogicController.borrowMvObject()
							.getAssociatedFileIds(mvId,
									infoEditor.getAssociatedStorage());
					for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
						index = associateFileList.getSelectionIndices()[j];
						// Remove selected indexes
						SilverBusinessLogicController.borrowFileObject()
								.deleteFile(temp[index],
										infoEditor.getAssociatedStorage());
					}

					/*
					 * Refresh by removing all elements in List and add all
					 * files belong to this project again.
					 */
					associateFileList.removeAll();

					for (int k = 0; k < SilverBusinessLogicController
							.borrowMvObject().getAssociatedFileIds(mvId,
									infoEditor.getAssociatedStorage()).length; k++) {
						try {
							log.info("reloading file");
							associateFileList
									.add(SilverBusinessLogicController
											.borrowFileObject()
											.getName(
													SilverBusinessLogicController
															.borrowMvObject()
															.getAssociatedFileIds(
																	mvId,
																	infoEditor
																			.getAssociatedStorage())[k],
													infoEditor
															.getAssociatedStorage()));
						} catch (Exception e2) {
							log.error(e2.getMessage(), e2);
						}
					}

				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
			}
		});

		Button createAssociateFile = new Button(mvAssociateFileGroup, SWT.PUSH
				| SWT.END);
		createAssociateFile.setText("Recreate");
		createAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to recreate.");
					return;
				}

				DirectoryDialog file = new DirectoryDialog(top.getShell(),
						SWT.SAVE);
				file.setText("Choose Directory :");
				file.setMessage("Select the Directory to save the Associate File:");
				final String directoryPath = file.open();

				int index;
				FileID[] temp;
				try {
					temp = SilverBusinessLogicController.borrowMvObject()
							.getAssociatedFileIds(mvId,
									infoEditor.getAssociatedStorage());
					String fileName = null;
					String path = null;
					for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
						index = associateFileList.getSelectionIndices()[j];
						// Remove selected indexes
						try {
							// get file name
							fileName = SilverBusinessLogicController
									.borrowFileObject().getName(temp[index],
											infoEditor.getAssociatedStorage());
							// combine recreate path
							path = directoryPath
									+ System.getProperty("file.separator")
									+ fileName;

							SilverBusinessLogicController.borrowFileObject()
									.getFileToLocalStorage(temp[index], path,
											infoEditor.getAssociatedStorage());
						} catch (Exception e1) {
							MessageDialog.openError(top.getShell(),
									"Error during recreate",
									"Unable to recreate file, file of the same name exists");
						}
					}

					/*
					 * Refresh by removing all elements in List and add all
					 * files belong to this project again.
					 */
					associateFileList.removeAll();

					for (int k = 0; k < SilverBusinessLogicController
							.borrowMvObject().getAssociatedFileIds(mvId,
									infoEditor.getAssociatedStorage()).length; k++) {
						log.info("reloading file");
						associateFileList
								.add(SilverBusinessLogicController
										.borrowFileObject()
										.getName(
												SilverBusinessLogicController
														.borrowMvObject()
														.getAssociatedFileIds(
																mvId,
																infoEditor
																		.getAssociatedStorage())[k],
												infoEditor
														.getAssociatedStorage()));
					}

				} catch (Exception e3) {
					log.error(e3.getMessage(), e3);
				}
			}
		});

		final ScenarioID baseLineScenarioId = SilverBusinessLogicController
				.borrowMvObject().getBaselineScenarioId(mvId,
						infoEditor.getAssociatedStorage());
		if (baseLineScenarioId == null) {
			final Label label = new Label(top, SWT.NONE);
			label.setText("&No baseline scenario is set");
		} else {
			final Group mvInfoGroup = new Group(top, SWT.NONE);
			mvInfoGroup.setText("&Baseline Scenario");
			GridLayout mvPaneComp = new GridLayout(2, true);

			GridData mvPaneData = new GridData(GridData.FILL_BOTH);
			mvPaneData.horizontalSpan = 3;
			mvInfoGroup.setLayoutData(mvPaneData);
			mvInfoGroup.setLayout(mvPaneComp);
			//
			// Label baseLineLabel = new Label(mvInfoGroup, SWT.NONE);
			// baseLineLabel.setText("&Baseline Scenario: ");
			// baseLineLabel.setLayoutData(new GridData(GridData.FILL,
			// GridData.FILL,
			// false, false, 2, 1));

			int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
					| SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
			Table table = new Table(mvInfoGroup, style);
			gridData = new GridData(GridData.FILL_BOTH);
			gridData.grabExcessVerticalSpace = false;
			gridData.horizontalSpan = 3;
			gridData.heightHint = 150;
			table.setLayoutData(gridData);
			table.setLinesVisible(true);
			table.setHeaderVisible(true);

			ParameterID[] parameterIds = SilverBusinessLogicController
					.borrowScenario().getParameterIds(baseLineScenarioId,
							infoEditor.getAssociatedStorage());

			TableViewer paramData = new TableViewer(table);
			TableContentProvider content = new TableContentProvider(
					parameterIds);
			paramData.setContentProvider(content);

			TableColumnLabelProvider columnsLabels = new TableColumnLabelProvider(
					infoEditor, baseLineScenarioId);
			columnsLabels.createColumns(paramData);

			paramData.getTable().setHeaderVisible(true);
			paramData.getTable().setLinesVisible(true);
			paramData.setInput(content);

			final Composite buttonsComp = new Composite(mvInfoGroup, SWT.NONE);
			buttonsComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL,
					GridData.CENTER, false, false, 2, 1));
			RowLayout rowLayout = new RowLayout();
			rowLayout.pack = false;
			buttonsComp.setLayout(rowLayout);

			final Button addInputFile = new Button(buttonsComp, SWT.PUSH);
			addInputFile.setText("Add Input Files");
			addInputFile.setLayoutData(new RowData());

			final Button recreate = new Button(buttonsComp, SWT.PUSH);
			recreate.setText("Recreate Source");
			recreate.setLayoutData(new RowData());
			// saveDescription.setLayoutData(new GridData(GridData.END,
			// GridData.CENTER, false, false, 3, 1));
			recreate.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {

					// log.info("Recreate the source file from the DB");

					DirectoryDialog file = new DirectoryDialog(mvInfoGroup
							.getShell(), SWT.SAVE);
					file.setText("Choose Directory :");
					file.setMessage("Select the Directory to save the Source File:");

					// set default output path to home
					file.setFilterPath(System.getProperty("user.home"));

					String path = file.open();
					String fileName;
					try {
						fileName = SilverBusinessLogicController
								.borrowMvObject().getSourceFileName(
										(ModelVersionID) getObjectId(),
										infoEditor.getAssociatedStorage());
						path = path + System.getProperty("file.separator")
								+ fileName;
						SilverBusinessLogicController.borrowMvObject()
								.recreateOriginalSourceFileToDisk(
										(ModelVersionID) infoEditor
												.getObjectId(), path,
										infoEditor.getAssociatedStorage());
					} catch (Exception e1) {
						log.error(e1.getMessage(), e1);
					}
				}
			});

			final Button recreateJar = new Button(buttonsComp, SWT.PUSH);
			recreateJar.setText("Recreate Jar File");
			recreateJar.setLayoutData(new RowData());
			recreateJar.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {

					// TODO consider FileDialog to use SWT.SAVE

					log.info("Recreate the Jar file from the DB");
					DirectoryDialog file = new DirectoryDialog(mvInfoGroup
							.getShell(), SWT.SAVE);

					file.setText("Choose Directory :");
					file.setMessage("Select the Directory to Save the Input file of this Model Version:");

					file.setFilterPath(System.getProperty("user.home"));

					String path = file.open();
					String fileName;
					try {
						fileName = SilverBusinessLogicController
								.borrowScenario().getOneInputFileName(
										baseLineScenarioId,
										infoEditor.getAssociatedStorage());

						// log.info("++++  The path of chosen dir: " +
						// path
						// +System.getProperty("file.separator") + fileName);

						path = path + System.getProperty("file.separator")
								+ fileName;

						SilverBusinessLogicController.borrowMvObject()
								.recreateOriginalInputFilesToDisk(
										(ModelVersionID) getObjectId(), path,
										infoEditor.getAssociatedStorage());
					} catch (Exception e2) {
						log.error(e2.getMessage(), e2);
					}

				}
			});

			addInputFile.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {

					SetInputFileToModelVersionDialog setIfileDialog = new SetInputFileToModelVersionDialog(
							top.getShell());
					int code = setIfileDialog.open();

					if (code == Window.OK) {
						boolean setFile = false;

						try {
							setFile = SilverBusinessLogicController
									.borrowMvObject()
									.interpretAnylogicSourceFileAndPackClassFilesToModelVersion(
											mvId,
											setIfileDialog.getSoureFilePath(),
											setIfileDialog.getJarFilePath(),
											infoEditor.getAssociatedStorage());
						} catch (Exception e1) {
							log.error(e1.getMessage(), e1);
						}

						if (setFile == false) {
							MessageDialog.openError(top.getShell(),
									"File Open Error",
									"The Input Files were not added to the Model Version.");
						} else {
							log.info("close page");
							// TODO this needs to be improved.
							infoEditor.getSite().getWorkbenchWindow()
									.getActivePage().closeAllEditors(true);
						}

						infoEditor.getAssociatedProjectView().updateTree();

					}
				}
			});

			if (SilverBusinessLogicController.borrowMvObject().getSourceFileId(
					mvId, infoEditor.getAssociatedStorage()) != null) {
				try {

					if (SilverBusinessLogicController.borrowMvObject()
							.getSourceFileId(mvId,
									infoEditor.getAssociatedStorage()) == null) {

						// Current ModelVersion does not have Input Files
						addInputFile.setEnabled(true);
						recreate.setEnabled(false);
						recreateJar.setEnabled(false);
						log.info(SilverBusinessLogicController.borrowMvObject()
								.getSourceFileId(mvId,
										infoEditor.getAssociatedStorage()));
						log.info("null");
					} else {
						// Current ModelVersion has Input Files
						recreate.setEnabled(true);
						recreateJar.setEnabled(true);
						addInputFile.setEnabled(false);

						FileID id = SilverBusinessLogicController
								.borrowMvObject().getSourceFileId(mvId,
										infoEditor.getAssociatedStorage());
						if (id != null)
							log.info(id);
					}
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
			}
		}

		SilverBusinessLogicController.returnAllMvObject();
		SilverBusinessLogicController.returnAllFileObject();

	}/* end of model version visitor */

	@Override
	public void visit(final ScenarioCollectionID scId) throws Exception {
		Group scAssociateFileGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		GridLayout layout = new GridLayout(2, false);
		scAssociateFileGroup.setLayoutData(gridData);
		scAssociateFileGroup.setLayout(layout);
		scAssociateFileGroup.setText("Associate Files");

		final List associateFileList = new List(scAssociateFileGroup, SWT.MULTI
				| SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.verticalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		associateFileList.setLayoutData(gridData);

		// ModelProjectLocalClient.getService().getAssociatedFileIds(mprojectId)
		// returns a FileID[]

		// FileID[] associatedFileIds = SilverBusinessLogicController
		// .borrowScObject().getAssociatedFileIds(scId,
		// infoEditor.getAssociatedStorage());
		try {
			ArrayList<String> fileNames = SilverBusinessLogicController
					.borrowScObject().getAssociatedFileName(scId,
							infoEditor.getAssociatedStorage());
			String[] a = new String[fileNames.size()];
			associateFileList.setItems(fileNames.toArray(a));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		Button addAssociateFile = new Button(scAssociateFileGroup, SWT.PUSH
				| SWT.END);
		addAssociateFile.setText("Add..");

		addAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog file = new FileDialog(top.getShell(), SWT.OPEN);
				file.setFilterExtensions(new String[] { "*.*" });
				file.setFilterNames(new String[] { "Associate files (*.*)" });
				file.setText("Load Associate File:");

				File addFile = new File(file.open());
				try {
					FileID tempId = SilverBusinessLogicController
							.borrowFileObject().createFile(addFile.getName(),
									"Associate File for" + scId.toString(),
									addFile.getAbsolutePath(),
									infoEditor.getAssociatedStorage());
					if (tempId == null) {
						MessageDialog.openError(
								top.getShell(),
								"Error adding associate files",
								"The associate file at "
										+ addFile.getAbsolutePath()
										+ " is not properly added.");
					}

					SilverBusinessLogicController.borrowFileObject()
							.addFileToScenarioCollection(tempId, scId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

				/*
				 * Refresh by removing all elements in List and add all files
				 * belong to this project again.
				 */
				associateFileList.removeAll();

				// TODO evaluate
				String[] temp = null;
				try {
					ArrayList<String> names = SilverBusinessLogicController
							.borrowScObject().getAssociatedFileName(scId,
									infoEditor.getAssociatedStorage());
					temp = new String[names.size()];
					names.toArray(temp);
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
				associateFileList.setItems(temp);

			}

		});

		Button removeAssociateFile = new Button(scAssociateFileGroup, SWT.PUSH
				| SWT.END);
		removeAssociateFile.setText("Remove");
		removeAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to remove.");
					return;
				}

				int index;

				try {
					FileID[] temp = SilverBusinessLogicController
							.borrowScObject().getAssociatedFileIds(scId,
									infoEditor.getAssociatedStorage());
					for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
						index = associateFileList.getSelectionIndices()[j];
						// Remove selected indexes

						SilverBusinessLogicController.borrowFileObject()
								.deleteFile(temp[index],
										infoEditor.getAssociatedStorage());

					}

					/*
					 * Refresh by removing all elements in List and add all
					 * files belong to this project again.
					 */
					associateFileList.removeAll();

					// TODO evaluate
					ArrayList<String> names = SilverBusinessLogicController
							.borrowScObject().getAssociatedFileName(scId,
									infoEditor.getAssociatedStorage());
					String[] temp1 = new String[names.size()];
					associateFileList.setItems(names.toArray(temp1));

				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
			}
		});

		Button createAssociateFile = new Button(scAssociateFileGroup, SWT.PUSH
				| SWT.END);
		createAssociateFile.setText("Recreate");
		createAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associateFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to recreate.");
					return;
				}

				DirectoryDialog file = new DirectoryDialog(top.getShell(),
						SWT.SAVE);
				file.setText("Choose Directory :");
				file.setMessage("Select the Directory to save the Associate File:");
				final String directoryPath = file.open();

				int index;
				try {
					FileID[] temp = SilverBusinessLogicController
							.borrowScObject().getAssociatedFileIds(scId,
									infoEditor.getAssociatedStorage());
					String fileName = null;
					String path = null;
					for (int j = 0; j < associateFileList.getSelectionIndices().length; j++) {
						index = associateFileList.getSelectionIndices()[j];
						// Remove selected indexes

						// get file name
						fileName = SilverBusinessLogicController
								.borrowFileObject().getName(temp[index],
										infoEditor.getAssociatedStorage());
						// combine recreate path
						path = directoryPath
								+ System.getProperty("file.separator")
								+ fileName;

						SilverBusinessLogicController.borrowFileObject()
								.getFileToLocalStorage(temp[index], path,
										infoEditor.getAssociatedStorage());

					}

					/*
					 * Refresh by removing all elements in List and add all
					 * files belong to this project again.
					 */
					associateFileList.removeAll();

					// TODO evaluate
					ArrayList<String> names = SilverBusinessLogicController
							.borrowScObject().getAssociatedFileName(scId,
									infoEditor.getAssociatedStorage());
					String[] temp1 = new String[names.size()];
					associateFileList.setItems(temp1);

				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

			}
		});

		final Group scInfoGroup = new Group(top, SWT.NONE);
		GridLayout scPaneComp = new GridLayout(2, true);

		GridData scPaneData = new GridData(GridData.FILL_HORIZONTAL);
		scPaneData.horizontalSpan = 3;
		scInfoGroup.setLayoutData(scPaneData);
		scInfoGroup.setLayout(scPaneComp);

		Label scenarioLabel = new Label(scInfoGroup, SWT.NONE);
		scenarioLabel.setText("&Scenario List:");
		scenarioLabel.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				false, false, 2, 1));

		int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
				| SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
		Table table = new Table(scInfoGroup, style);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.grabExcessVerticalSpace = false;
		gridData.heightHint = 150;
		gridData.horizontalSpan = 2;
		table.setLayoutData(gridData);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		final TableViewer scenarioData = new TableViewer(table);

		/*
		 * TODO finsh up the actual content once the params are available this
		 * table contains fake data for now have to pass in the array hashmap
		 * object and that will be the element
		 */
		final ScenarioTableContentProvider content = new ScenarioTableContentProvider();

		// Obtain ModelObjectChildren from the Adapter

		content.setScenarioIds((ScenarioID[]) getObjectId()
				.getChildrenObjectIds(infoEditor.getAssociatedStorage()));

		scenarioData.setContentProvider(content);

		ScenarioTableColumnLabelProvider columnsLabels = new ScenarioTableColumnLabelProvider(
				infoEditor);
		columnsLabels.createColumns(scenarioData);

		scenarioData.getTable().setHeaderVisible(true);
		scenarioData.getTable().setLinesVisible(true);

		scenarioData.setInput(content);

		Label newScenarioLabel = new Label(scInfoGroup, SWT.NONE);
		newScenarioLabel
				.setText("&Create New Scenario from Baseline Scenario:");
		newScenarioLabel.setLayoutData(new GridData(GridData.FILL,
				GridData.FILL, false, false, 1, 1));

		// Implementation of createNewScenario button under Scenario List.
		Button createNewScenario = new Button(scInfoGroup, SWT.CENTER);
		createNewScenario.setText("Add New Scenario");
		createNewScenario.setLayoutData(new GridData(GridData.END,
				GridData.CENTER, false, false));
		createNewScenario.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				CreateScenarioDialog createScDialog = new CreateScenarioDialog(
						scInfoGroup.getShell(),
						(ScenarioCollectionID) getObjectId(), infoEditor
								.getAssociatedStorage());
				int i;
				int code = createScDialog.open();
				if (code == Window.OK) {

					/*
					 * not sure what this selection is about been awhile trying
					 * to get a handle on it I think it might have to do with
					 * the selection of items picture from the GUI to enable
					 * options
					 */

					// TODO: figure this out, what does
					// CreateScenarioTableContentProvider do?
					Hashtable<String, String>[] parameterData = CreateScenarioTableContentProvider
							.getNewScenarioData();
					ParameterID[] paramId = CreateScenarioTableContentProvider
							.getParameterIDData();
					/*
					 * straight up call to the DB to insert the data and return
					 * a model project
					 */

					ScenarioID scenarioID = null;
					FileID fileID = null;
					try {
						scenarioID = SilverBusinessLogicController
								.borrowScenario()
								.createGenericScenarioAndParameterSet(
										createScDialog.getScenarioName(),
										createScDialog.getScenarioCreator(),
										createScDialog.getScenarioDescription(),
										createScDialog.getModelVersionID(),
										(ScenarioCollectionID) getObjectId(),
										infoEditor.getAssociatedStorage());
						SilverBusinessLogicController
								.returnLastScenarioObject();

						// Iterate through File List and Add Associate Files to
						// Scenario
						if (createScDialog.getAssociateFileSelection()) {
							log.info("adding associate files to" + scenarioID);
							String associateFileLocation;
							File associateFile = null;
							for (int j = 0; j < createScDialog
									.getAssociateFileArray().length; j++) {
								associateFileLocation = createScDialog
										.getAssociateFileArray()[j];
								associateFile = new File(associateFileLocation);

								if (!associateFile.canRead()) {
									throw new IOException(
											"Attempting to parse source file failed. Could not open: "
													+ associateFileLocation);
								}
								fileID = SilverBusinessLogicController
										.borrowFileObject()
										.createFile(
												associateFile.getName(),
												"Associate File for"
														+ scenarioID.toString(),
												associateFile.getAbsolutePath(),
												infoEditor
														.getAssociatedStorage());
								SilverBusinessLogicController
										.borrowFileObject()
										.addFileToScenario(
												fileID,
												scenarioID,
												infoEditor
														.getAssociatedStorage());
							}
						}
					} catch (Exception scenario_e) {
						log.error(scenario_e.getMessage(), scenario_e);
					}

					for (i = 0; i < parameterData.length; i++) {
						try {
							SilverBusinessLogicController
									.borrowParameterObject()
									.addParamteterToScenario(
											paramId[i],
											scenarioID,
											parameterData[i]
													.get(SilverNameEnums.VALUE
															.name()),
											parameterData[i]
													.get(SilverNameEnums.COMMENT
															.name()),
											infoEditor.getAssociatedStorage());
							// update ContentProvider
							content.setScenarioIds((ScenarioID[]) getObjectId()
									.getChildrenObjectIds(
											infoEditor.getAssociatedStorage()));
						} catch (Exception parameter_e) {
							log.error(parameter_e.getMessage(), parameter_e);
						}

						// force reset content
						scenarioData.setInput(content);

					}

					/* refresh to entire tree automatically after an update */
					// scenarioID returns 'sc1' from toString()
					infoEditor.getAssociatedProjectView().updateTree();

				}

			}
		});

	}

	/**
	 * A method that display the appropriate data for the scenario selected by
	 * the user. This data is retrieved from the database The parameter data is
	 * displayed in a table viewer and is not editable at this point.
	 * 
	 * @param top
	 *            the composite of this editor pane
	 * @param sId
	 *            scenario Id for the selected scenarioId
	 * @param parameterIds
	 *            array of paramterIds associated with this scenario
	 */
	@Override
	public void visit(final ScenarioID sId) throws Exception {
		/*
		 * creating separate composite so it can span the original for alignment
		 * purposes my want to play with the number of columns
		 */

		Group sAssociateFileGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		GridLayout layout = new GridLayout(2, false);
		sAssociateFileGroup.setLayoutData(gridData);
		sAssociateFileGroup.setLayout(layout);
		sAssociateFileGroup.setText("Associate Files");

		final List associatedFileList = new List(sAssociateFileGroup, SWT.MULTI
				| SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.verticalSpan = 3;
		gridData.horizontalAlignment = SWT.FILL;
		associatedFileList.setLayoutData(gridData);

		PopulateAssociatedFileList(sId, associatedFileList);

		Button addAssociateFile = new Button(sAssociateFileGroup, SWT.PUSH
				| SWT.END);
		addAssociateFile.setText("Add..");

		addAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog file = new FileDialog(top.getShell(), SWT.OPEN);
				file.setFilterExtensions(new String[] { "*.*" });
				file.setFilterNames(new String[] { "Associate files (*.*)" });
				file.setText("Load Associate File:");

				File addFile = new File(file.open());
				try {
					FileID tempId = SilverBusinessLogicController
							.borrowFileObject().createFile(addFile.getName(),
									"Associate File for" + sId.toString(),
									addFile.getAbsolutePath(),
									infoEditor.getAssociatedStorage());
					if (tempId == null) {
						MessageDialog.openError(
								top.getShell(),
								"Error adding associate files",
								"The associate file at "
										+ addFile.getAbsolutePath()
										+ " is not properly added.");
					}
					SilverBusinessLogicController.borrowFileObject()
							.addFileToScenario(tempId, sId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}

				RepopulateAssociatedFileList(sId, associatedFileList);
			}

		});

		Button removeAssociateFile = new Button(sAssociateFileGroup, SWT.PUSH
				| SWT.END);
		removeAssociateFile.setText("Remove");
		removeAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associatedFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to remove.");
					return;
				}

				int index;
				FileID[] temp = null;
				try {
					temp = SilverBusinessLogicController.borrowScenario()
							.getAssociatedFileIds(sId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e2) {
					log.error(e2.getMessage(), e2);
				}
				for (int j = 0; j < associatedFileList.getSelectionIndices().length; j++) {
					index = associatedFileList.getSelectionIndices()[j];
					// Remove selected indexes
					try {
						SilverBusinessLogicController.borrowFileObject()
								.deleteFile(temp[index],
										infoEditor.getAssociatedStorage());
					} catch (Exception e1) {
						log.error(e1.getMessage(), e1);
					}
				}

				RepopulateAssociatedFileList(sId, associatedFileList);
			}
		});

		Button createAssociateFile = new Button(sAssociateFileGroup, SWT.PUSH
				| SWT.END);
		createAssociateFile.setText("Recreate");
		createAssociateFile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (associatedFileList.getSelectionCount() == 0) {
					MessageDialog.openInformation(top.getShell(),
							"No File Selected",
							"Please select one or more files from the list to recreate.");
					return;
				}

				DirectoryDialog file = new DirectoryDialog(top.getShell(),
						SWT.SAVE);
				file.setText("Choose Directory :");
				file.setMessage("Select the Directory to save the Associate File:");
				final String directoryPath = file.open();

				int index;
				FileID[] temp = null;
				try {
					temp = SilverBusinessLogicController.borrowScenario()
							.getAssociatedFileIds(sId,
									infoEditor.getAssociatedStorage());
				} catch (Exception e2) {
				}
				String fileName = null;
				String path = null;
				for (int j = 0; j < associatedFileList.getSelectionIndices().length; j++) {
					index = associatedFileList.getSelectionIndices()[j];
					// Remove selected indexes
					try {
						// get file name
						fileName = SilverBusinessLogicController
								.borrowFileObject().getName(temp[index],
										infoEditor.getAssociatedStorage());
						// combine recreate path
						path = directoryPath
								+ System.getProperty("file.separator")
								+ fileName;

						SilverBusinessLogicController.borrowFileObject()
								.getFileToLocalStorage(temp[index], path,
										infoEditor.getAssociatedStorage());
					} catch (Exception e1) {
						log.error(e1.getMessage(), e1);
						MessageDialog.openError(top.getShell(),
								"Error during recreate",
								"Unable to recreate file, file of the same name exists");
					}
				}

				RepopulateAssociatedFileList(sId, associatedFileList);
			}
		});

		final Group scenarioInfoGroup = new Group(top, SWT.NONE);

		GridLayout sPaneComp = new GridLayout(3, true);

		GridData sPaneData = new GridData(GridData.FILL_HORIZONTAL);
		sPaneData.horizontalSpan = 3;
		scenarioInfoGroup.setLayoutData(sPaneData);
		scenarioInfoGroup.setLayout(sPaneComp);

		Label parameterLabel = new Label(scenarioInfoGroup, SWT.NONE);
		parameterLabel.setText("&Parameters: ");
		parameterLabel.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				false, false, 3, 1));

		// TODO REFACTOR OUT TABLE
		int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
				| SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
		Table table = new Table(scenarioInfoGroup, style);
		gridData = new GridData(GridData.FILL_BOTH);
		gridData.grabExcessVerticalSpace = false;
		gridData.heightHint = 150;
		gridData.horizontalSpan = 3;
		table.setLayoutData(gridData);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableViewer paramData = new TableViewer(table);
		TableContentProvider content = new TableContentProvider(
				SilverBusinessLogicController.borrowScenario().getParameterIds(
						sId, infoEditor.getAssociatedStorage()));
		paramData.setContentProvider(content);

		TableColumnLabelProvider columnsLabels = new TableColumnLabelProvider(
				infoEditor, sId);
		columnsLabels.createColumns(paramData);

		paramData.getTable().setHeaderVisible(true);
		paramData.getTable().setLinesVisible(true);
		paramData.setInput(content);

		// establish label for the simulation run
		Label runSimLabel = new Label(scenarioInfoGroup, SWT.NONE);
		runSimLabel.setText("&Run Simulation:");
		runSimLabel.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				false, false, 2, 1));

		// get the simulation type (i.e. type of simulation platform)
		String strSimulationType = null;
		try {
			strSimulationType = SilverBusinessLogicController.borrowScenario()
					.getParentVersionSimulationType(sId,
							infoEditor.getAssociatedStorage());
		} catch (Exception e2) {
			log.error(e2.getMessage(), e2);
		}

		// establish button for the simulation run

		EstablishRunSimulationButton(strSimulationType, sId, scenarioInfoGroup,
				associatedFileList, infoEditor.getAssociatedStorage());

	}/* end of the scenario */

	private void RepopulateAssociatedFileList(final ScenarioID scenarioId,
			final List associatedFileList) {
		/*
		 * Refresh by removing all elements in List and add all files belong to
		 * this project again.
		 */
		associatedFileList.removeAll();
		try {
			PopulateAssociatedFileList(scenarioId, associatedFileList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void PopulateAssociatedFileList(final ScenarioID scenarioId,
			final List associatedFileList) throws Exception {
		for (int j = 0; j < SilverBusinessLogicController.borrowScenario()
				.getAssociatedFileIds(scenarioId,
						infoEditor.getAssociatedStorage()).length; j++) {
			try {
				log.info("reloading file");
				associatedFileList
						.add(SilverBusinessLogicController
								.borrowFileObject()
								.getName(
										SilverBusinessLogicController
												.borrowScenario()
												.getAssociatedFileIds(
														scenarioId,
														infoEditor
																.getAssociatedStorage())[j],
										infoEditor.getAssociatedStorage()));
			} catch (FileNotFoundException notFound) {
				log.error(notFound.getMessage(), notFound);
			} catch (Exception e2) {
				log.error(e2.getMessage(), e2);
			}
		}

	}

	private void EstablishRunSimulationButton(final String strSimulationType,
			final ScenarioID scenarioId, final Group scenarioInfoGroup,
			final List associatedFileList, final StorageI storage) {
		Button runSimulation = new Button(scenarioInfoGroup, SWT.CENTER);
		runSimulation.setEnabled(true);

		if (strSimulationType == null) {
			runSimulation.setEnabled(false);
		}
		runSimulation.setText("Run " + strSimulationType + " Model");
		// runSimLabel.setBackground(top.getDisplay().getSystemColor(SWT.COLOR_RED));
		runSimulation.setLayoutData(new GridData(GridData.END, GridData.CENTER,
				false, false));
		// editName.addSelectionListener(new
		// RenameButtonSelectionAdapter(parent, getModelObjectID(),
		// getModelObjectName())),

		runSimulation
				.setToolTipText("Run the simulation specified in this Scenario.");
		runSimulation.addSelectionListener(new SelectionAdapter() {
			// public void widgetSelected(SelectionEvent e){
			//
			// // run scenario
			// SilverAdapterFactory.getInstance().runScenarioScreenShot(getObjectId());
			//
			// }
			@Override
			public void widgetSelected(SelectionEvent e) {

				// TODO finish up runSimulation button
				// Verify if it's Vensim
				try {
					if (isVensimScenario(scenarioId, storage)) {
						if (isWindowsPlatform()) {

							RunVensimSimulationDialog d = new RunVensimSimulationDialog(
									scenarioInfoGroup.getShell());

							if (d.open() == Window.OK) {
								SilverBusinessLogicController
										.borroweSilverServiceObject()
										.runVensimScenario(scenarioId,
												d.simName(), storage);

								// TODO: this should be trajectory file
								FileID id = SilverBusinessLogicController
										.borrowFileObject().createFile(
												d.simName() + ".vdf",
												"trajectory file",
												d.simName() + ".vdf", storage);
								SilverBusinessLogicController
										.borrowFileObject().addFileToScenario(
												id, scenarioId, storage);

								RepopulateAssociatedFileList(scenarioId,
										associatedFileList);
							}
							// if user did not press ok, don't do anything
						} else {
							MessageDialog
									.openInformation(infoEditor.getSite()
											.getShell(),
											"Unsupported Simulation",
											"Please consider running this simulation in Windows platform.");
						}
					} else if (isAnylogicScenario(scenarioId, storage)) {
						// TODO: should verify that this is an anylogic scenario
						RunAnylogicSimulationDialog d = new RunAnylogicSimulationDialog(
								scenarioInfoGroup.getShell());
						d.open();

						if (d.selection() == RunAnylogicSimulationDialog.NORMAL_SIM) {
							SilverBusinessLogicController
									.borroweSilverServiceObject()
									.runAnylogicScenario(
											scenarioId,
											SilverBusinessLogicController
													.getPreferenceEntry(SilverPreferenceEntries.ANYLOGIC_PATH),
											storage);
						} else if (d.selection() == RunAnylogicSimulationDialog.SCREENSHOT_SIM) {
							SilverBusinessLogicController
									.borroweSilverServiceObject()
									.runAnylogicScenarioScreenShot(
											scenarioId,
											SilverBusinessLogicController
													.getPreferenceEntry(SilverPreferenceEntries.ANYLOGIC_PATH),
											storage);
						} else if (d.selection() == RunAnylogicSimulationDialog.LOGGING_SIM) {
							SilverBusinessLogicController
									.borroweSilverServiceObject()
									.runAnylogicScenarioLogging(
											scenarioId,
											SilverBusinessLogicController
													.getPreferenceEntry(SilverPreferenceEntries.ANYLOGIC_PATH),
											storage);
						}
					}

					SilverBusinessLogicController
							.returnAllSilverServiceObject();
					SilverBusinessLogicController.returnAllFileObject();
				} catch (Exception e1) {
					log.error(e1.getMessage(), e1);
				}
			}
		});
	}

	private boolean isVensimScenario(final ScenarioID scenarioId,
			StorageI storage) throws Exception {
		return scenarioId.getTypeFromDatabase(storage).equals("VENSIM");
	}

	private boolean isAnylogicScenario(final ScenarioID scenarioId,
			StorageI storage) throws Exception {
		return scenarioId.getTypeFromDatabase(storage).equals("ANYLOGIC");
	}

	private boolean isWindowsPlatform() {
		return System.getProperty("os.name").startsWith("Windows");
	}

}
